package com.kaifamiao.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.logging.Logger;

@WebServlet( name = "prepared-servlet",
             urlPatterns = "/prepared/servlet",
             loadOnStartup = 1 )
public class PreparedServlet extends HttpServlet {

    private static final String className = PreparedServlet.class.getName();
    private static final Logger logger = Logger.getLogger( className );

    private String servletName;

    @Override
    public void init() throws ServletException {
        servletName = this.getServletName();
        logger.info( String.format("初始化[%s]实例(%s)", this, servletName ) );
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logger.info( String.format("[%s]实例(%s)正在提供服务", this, servletName) );
        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html; charset=UTF-8" );
        PrintWriter out = response.getWriter();
        out.println( "<p align=\"center\">" + LocalDateTime.now() + "</p>" );
    }

    @Override
    public void destroy() {
        logger.info( String.format("释放[%s]实例(%s)占用的资源", this, servletName) );
    }

}
